{extend name="public/base" /}
{block name="style"}
    <style>
        /* 搜索框 */
        .wy-search-box {
            padding: 10px;
            background-color: #f5f5f5;
        }
        .weui-search-bar {
            background-color: #fff;
            border-radius: 20px;
            padding: 6px 15px;
            display: -webkit-box;
            display: -webkit-flex;
            display: flex;
            align-items: center;
        }
        .search-icon {
            color: #888;
            margin-right: 8px;
            flex-shrink: 0;
        }
        .search-input {
            -webkit-box-flex: 1;
            -webkit-flex: 1;
            flex: 1;
            border: none;
            outline: none;
            font-size: 14px;
            color: #333;
            height: 24px;
        }
        .search-input::placeholder {
            color: #ccc;
        }


        .sort-btn {
            color: #888;
            font-size: 13px;
            text-decoration: none;
            display: -webkit-box;
            display: -webkit-flex;
            display: flex;
            align-items: center;
        }
        .sort-btn i {
            margin-left: 4px;
            font-size: 12px;
        }

        /* 表头样式（增加与列表的间距） */
        .stock-header {
            display: -webkit-box;
            display: -webkit-flex;
            display: flex;
            align-items: center;
            padding: 10px 0; /* 增加内边距，避免与列表项过近 */
            border-bottom: 1px solid #eee;
            margin-bottom: 12px; /* 加大与列表的距离 */
        }
        .header-name {
            -webkit-box-flex: 1;
            -webkit-flex: 1;
            flex: 1;
            font-size: 13px;
            color: #888;
            padding-left: 32px; /* 与列表项图标+间距严格对齐 */
        }
        .header-price {
            width: 80px;
            text-align: right;
            padding-right: 10px;
            font-size: 13px;
            color: #888;
            flex-shrink: 0;
        }
        .header-change {
            min-width: 50px;
            text-align: center;
            font-size: 13px;
            color: #888;
            flex-shrink: 0;
        }
        /* 列表项样式（增加行高和间距，避免内容拥挤） */


    </style>
{/block}
{block name="content"}
<!-- 头部导航（带返回按钮） -->
<div class="header">
    <a href="javascript:void(0);" class="back-btn">
        <i class="fa fa-angle-left" style="font-size: 24px;"></i>
    </a>
    <h1 class="header-title">所有币种</h1>
</div>
<div class='weui-content'>
    <!-- 搜索框 -->
    <div class="wy-search-box">
        <div class="weui-search-bar">
            <i class="fa fa-search search-icon"></i>
            <input type="text" class="search-input" placeholder="搜索币种名称或代码">
        </div>
    </div>
    <!-- 所有币种列表（带表头） -->
    <div class="wy-Module">
        <div class="wy-Module-tit">
            <span>币种列表</span>
            <a href="javascript:sortList()" class="sort-btn">
                涨幅排序 <i class="fa fa-sort"></i>
            </a>
        </div>
        <div class="wy-Module-con">
            <!-- 表头 -->
            <div class="stock-header table-row">
                <div class="header-name table-cell">名称</div>
                <div class="header-price table-cell">价格(USDT)</div>
                <div class="header-change table-cell">涨跌幅</div>
            </div>
            <!-- 列表内容 -->
            <ul class="stock-list" id="coinList">
                    {foreach name="marketList" item="vo"}
                        <li class="table-row down">
                            <a href="/trade/{$vo.code}.html"  class="stock-link {$vo.code}" data-code="{$vo.code}">
                                <div class="stock-info table-cell">
                                    <div class="stock-name">
                                        <img src="{$vo.icon}" class="stock-icon" alt="{$vo.code}">
                                        {$vo.code}
                                    </div>
                                    <div class="stock-volume">/usdt</div>
                                </div>
                                <div class="stock-price-wrap table-cell">
                                    <span class="stock-price">{$vo.close|h_format_large_number}</span>
                                </div>
                                <div class="stock-change-wrap table-cell">
                                    {if $vo.change < 0}
                                        <span class="stock-change up">{$vo.change}%</span>
                                    {else /}
                                        <span class="stock-change down">+{$vo.change}%</span>
                                    {/if}
                                </div>
                            </a>
                        </li>
                    {/foreach}

                </ul>
            <div style="margin-top: 20px;"></div>
        </div>
    </div>
</div>

<footer class="wy-footer">
    <a href="/" class="footer-nav ">
        <i class="fa fa-home"></i>
        <span>首页</span>
    </a>
    <a href="javascript:void(0);" class="footer-nav active">
        <i class="fa fa-line-chart"></i>
        <span>行情</span>
    </a>
    <a href="/asset.html" class="footer-nav">
        <i class="fa fa-cube"></i>
        <span>资产</span>
    </a>
    <a href="/member.html" class="footer-nav"> <!-- 当前页高亮 -->
        <i class="fa fa-user"></i>
        <span>我的</span>
    </a>
</footer>
{/block}
{block name="script"}
<script>
    // 排序功能
    let sortAsc = true;
    function sortList() {
        const list = $("#coinList");
        const items = Array.from(list.find('li'));
        // 按涨跌幅数值排序
        items.sort((a, b) => {
            const valA = parseFloat(a.querySelector('.stock-change').textContent);
            const valB = parseFloat(b.querySelector('.stock-change').textContent);
            return sortAsc ? valB - valA : valA - valB;
        });
        // 重新排列DOM
        items.forEach(item => list.append(item));
        sortAsc = !sortAsc;
        $('.sort-btn i').className = sortAsc ? 'fa fa-sort-amount-desc' : 'fa fa-sort-amount-asc';
    }
    // 搜索功能
    $('.search-input').on('input', function(e) {
        const keyword = e.target.value.toLowerCase();
        const items = $('.stock-list').find("li");
        $.each(items,function (index,item){
            const name = $(item).find('.stock-name').text().toLowerCase();
            const symbol =  $(item).find('.stock-symbol').text().toLowerCase();
            const isMatch = name.includes(keyword) || symbol.includes(keyword);
            $(item).css("display",isMatch ? 'flex' : 'none');
        })
    });
</script>
<script>
    let webSocket = null;
    let isConnect = false; // 连接状态标志位
    let rec = null; // 用于存储延迟重连的定时器
    const marketList =JSON.parse('{$marketList|raw|json_encode}');
    const code = marketList.map(function (item){
        return item.code;
    });
    console.log(code);
    createWebSocket()

    function createWebSocket() {
        try {
            const wsUri = 'ws://127.0.0.1:8082'; // WebSocket服务器地址
            webSocket = new WebSocket(wsUri);
            initWebSocket();
        } catch (e) {
            console.log('尝试创建连接失败' + e);
            reConnect(); // 创建连接失败时触发重连
        }
    }

    function initWebSocket() {
        webSocket.onopen = function (e) {
            console.log('WebSocket连接已打开');
            isConnect = true; // 更新连接状态标志位
            webSocket.send(JSON.stringify({
                "type": "init",
                "data": code
            }));
            // 可以在这里启动心跳检测等逻辑...
        };
        webSocket.onclose = function (e) {
            console.log('WebSocket连接已关闭');
            isConnect = false; // 更新连接状态标志位
            reConnect(); // 连接关闭时触发重连
        };
        webSocket.onmessage = function (e) {
            // 处理接收到的消息...
            data = JSON.parse(e.data)
            if (data["type"]=="pong") {
                webSocket.send(JSON.stringify({
                    "type": "ping"
                }));
            }
            if (data["type"] == "market") {
                $.each(data["data"], function (key, v) {
                   var  val = v;
                    symbol = val["code"];
                    close = val["close"];
                    change = val["change"];
                    obj = $("." + symbol);
                    obj.find(".stock-price").text(close);
                    obj.find(".stock-change").removeClass("up").removeClass("down");
                    if (change < 0) {
                        obj.find(".stock-change").addClass("up");
                        obj.find(".stock-change").text(change + "%");
                    } else {
                        obj.find(".stock-change").addClass("down");
                        obj.find(".stock-change").text("+"+change + "%");
                    }
                })
            }
        };
        webSocket.onerror = function (e) {
            console.log('WebSocket连接发生错误');
            isConnect = false; // 更新连接状态标志位
            reConnect(); // 连接错误时触发重连
        };
    }

    function reConnect() {
        if (isConnect) return; // 如果已经连接上则不再重连
        if (rec) clearTimeout(rec); // 清除之前的重连定时器（如果存在）
        rec = setTimeout(function () {
            createWebSocket(); // 延迟一段时间后尝试重新建立连接
        }, 5000); // 设置延迟时间为5秒（可根据实际需求调整）
    }
</script>
{/block}